//
//  AppManager.m
//  HiZhua
//
//  Created by Jpwang on 2017/8/7.
//  Copyright © 2017年 Jpwang. All rights reserved.
//
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <sys/utsname.h>
#import <sys/param.h>
#import <sys/mount.h>
#import <sys/sysctl.h>
#import <mach/mach.h>
#import "AppManager.h"


#pragma mark ************************************************************************************************************
#pragma mark 服务端配置的错误码
#pragma mark ************************************************************************************************************
@implementation ErrorCode
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{@"code":@"code",
             @"desc":@"desc"};
}
@end


#pragma mark ************************************************************************************************************
#pragma mark 服务端配置的错误码处理工具
#pragma mark ************************************************************************************************************
@interface ErrorCodeUtil() {
    NSMutableArray *errorCodeArr;
    NSNumber *clientType;
    NSString *createTime;
    NSNumber *errorId;
    NSString *updateTime;
    NSString *version;
    //    clientType = 1;
    //    createTime = "2017-08-29 00:00:00";
    //    id = 1;
    //    updateTime = "2017-08-29 00:00:00";
    //    version = 10;
}
@end

@implementation ErrorCodeUtil

+ (ErrorCodeUtil *)shareInstance {
    static ErrorCodeUtil *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[ErrorCodeUtil alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        version = @"0";
        errorCodeArr = [[NSMutableArray alloc] init];
        id data = getValueByKey(@"error_code");
        [self setData:data];
    }
    return self;
}

- (void)setData:(NSDictionary *)data {
    if (data) {
        @try {
            saveValueByKey(data, (@"error_code"));
            clientType = data[@"clientType"];
            createTime = data[@"createTime"];
            errorId = data[@"id"];
            updateTime = data[@"updateTime"];
            version = [NSString stringWithFormat:@"%@",data[@"clientType"]];
            NSArray *arr = string2Json(data[@"config"]);
            NSError *error = nil;
            NSArray *dataArr = [MTLJSONAdapter modelsOfClass:[ErrorCode class] fromJSONArray:arr error:&error];
            [errorCodeArr removeAllObjects];
            [errorCodeArr addObjectsFromArray:dataArr];
        } @catch (NSException *exception) {
        
        }
    }
}

- (NSString *)version {
    return version;
}

- (NSString *)descByCode:(NSString *)code {
    @try {
        for (int i=0; i<errorCodeArr.count; i++) {
            ErrorCode *errorCode = errorCodeArr[i];
            if ([errorCode.code isEqualToString:code]) {
                return errorCode.desc;
            }
        }
    } @catch (NSException *exception) {
        return nil;
    }
    return nil;
}

@end


#pragma mark ************************************************************************************************************
#pragma mark DeviceInfo
#pragma mark ************************************************************************************************************
@implementation DeviceInfo

// 获取运营商名称
-(NSString *)carrierName {
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
    if (!carrier.isoCountryCode) {
        return @"没有SIM卡";
    } else {
        return [carrier carrierName];
    }
}

- (NSString *)osBuildTime {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:[NSProcessInfo processInfo].systemUptime];
    return [NSString stringWithFormat:@"%@",date];
}

- (NSString *)osName {
    return [[UIDevice currentDevice] systemName];
}

- (NSString *)osVersion{
    return [[UIDevice currentDevice] systemVersion];
}

- (NSString *)appName {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleDisplayName"];
}

- (NSString *)appVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}

- (NSString *)appBuild {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleVersion"];
}

- (NSString*)model {
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if([platform isEqualToString:@"iPhone1,1"]) return@"iPhone 2G";
    
    if([platform isEqualToString:@"iPhone1,2"]) return@"iPhone 3G";
    
    if([platform isEqualToString:@"iPhone2,1"]) return@"iPhone 3GS";
    
    if([platform isEqualToString:@"iPhone3,1"]) return@"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,2"]) return@"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,3"]) return@"iPhone 4";
    
    if([platform isEqualToString:@"iPhone4,1"]) return@"iPhone 4S";
    
    if([platform isEqualToString:@"iPhone5,1"]) return@"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,2"]) return@"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,3"]) return@"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone5,4"]) return@"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone6,1"]) return@"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone6,2"]) return@"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone7,1"]) return@"iPhone 6 Plus";
    
    if([platform isEqualToString:@"iPhone7,2"]) return@"iPhone 6";
    
    if([platform isEqualToString:@"iPhone8,1"]) return@"iPhone 6s";
    
    if([platform isEqualToString:@"iPhone8,2"]) return@"iPhone 6s Plus";
    
    if([platform isEqualToString:@"iPhone8,4"]) return@"iPhone SE";
    
    if([platform isEqualToString:@"iPhone9,1"]) return@"iPhone 7";
    
    if([platform isEqualToString:@"iPhone9,2"]) return@"iPhone 7 Plus";
    
    if([platform isEqualToString:@"iPhone10,1"]) return@"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,4"]) return@"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,2"]) return@"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,5"]) return@"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,3"]) return@"iPhone X";
    
    if([platform isEqualToString:@"iPhone10,6"]) return@"iPhone X";
    
    if([platform isEqualToString:@"iPod1,1"]) return@"iPod Touch 1G";
    
    if([platform isEqualToString:@"iPod2,1"]) return@"iPod Touch 2G";
    
    if([platform isEqualToString:@"iPod3,1"]) return@"iPod Touch 3G";
    
    if([platform isEqualToString:@"iPod4,1"]) return@"iPod Touch 4G";
    
    if([platform isEqualToString:@"iPod5,1"]) return@"iPod Touch 5G";
    
    if([platform isEqualToString:@"iPad1,1"]) return@"iPad 1G";
    
    if([platform isEqualToString:@"iPad2,1"]) return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,2"]) return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,3"]) return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,4"]) return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,5"]) return@"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad2,6"]) return@"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad2,7"]) return@"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad3,1"]) return@"iPad 3";
    
    if([platform isEqualToString:@"iPad3,2"]) return@"iPad 3";
    
    if([platform isEqualToString:@"iPad3,3"]) return@"iPad 3";
    
    if([platform isEqualToString:@"iPad3,4"]) return@"iPad 4";
    
    if([platform isEqualToString:@"iPad3,5"]) return@"iPad 4";
    
    if([platform isEqualToString:@"iPad3,6"]) return@"iPad 4";
    
    if([platform isEqualToString:@"iPad4,1"]) return@"iPad Air";
    
    if([platform isEqualToString:@"iPad4,2"]) return@"iPad Air";
    
    if([platform isEqualToString:@"iPad4,3"]) return@"iPad Air";
    
    if([platform isEqualToString:@"iPad4,4"]) return@"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,5"]) return@"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,6"]) return@"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,7"]) return@"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad4,8"]) return@"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad4,9"]) return@"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad5,1"]) return@"iPad Mini 4";
    
    if([platform isEqualToString:@"iPad5,2"]) return@"iPad Mini 4";
    
    if([platform isEqualToString:@"iPad5,3"]) return@"iPad Air 2";
    
    if([platform isEqualToString:@"iPad5,4"]) return@"iPad Air 2";
    
    if([platform isEqualToString:@"iPad6,3"]) return@"iPad Pro 9.7";
    
    if([platform isEqualToString:@"iPad6,4"]) return@"iPad Pro 9.7";
    
    if([platform isEqualToString:@"iPad6,7"]) return@"iPad Pro 12.9";
    
    if([platform isEqualToString:@"iPad6,8"]) return@"iPad Pro 12.9";
    
    if([platform isEqualToString:@"i386"]) return@"iPhone Simulator";
    
    if([platform isEqualToString:@"x86_64"]) return@"iPhone Simulator";
    
    return platform;
}

// 获取当前设备可用内存(单位：MB）
- (double)freeMemory {
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;
}

// 获取当前设备总内存
- (double)totalMemory {
    return [NSProcessInfo processInfo].physicalMemory/1000.0/1000;
}


// 获取当前任务所占用的内存（单位：MB）
- (double)usedMemory {
    task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
    kern_return_t kernReturn = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&taskInfo, &infoCount);
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    return taskInfo.resident_size / 1024.0 / 1024.0;
}

//存储空间总大小
-(double)totalDiskSpace {
    struct statfs buf;
    unsigned long long freeSpace = -1;
    if (statfs("/var", &buf) >= 0)
    {
        freeSpace = (unsigned long long)(buf.f_bsize * buf.f_blocks);
    }
    return freeSpace/1000/1000;
}

//存储空间可用大小
-(double)freeDiskSpace {
    struct statfs buf;
    unsigned long long freeSpace = -1;
    if (statfs("/var", &buf) >= 0) {
        freeSpace = (unsigned long long)(buf.f_bsize * buf.f_bavail);
    }
    return freeSpace/1000.0/1000.0;
}

//手机系统大小、可用空间大小
-(uint64_t)getFreeDiskspace {
    uint64_t totalSpace = 0.0f;
    uint64_t totalFreeSpace = 0.0f;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    
    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes floatValue];
        totalFreeSpace = [freeFileSystemSizeInBytes floatValue];
        NSLog(@"Memory Capacity of %f GB with %f GB FreeMemoryAvailable.", ((totalSpace/1024.0)/1024.0/1024.0), ((totalFreeSpace/1024.0)/1024.0/1024.0));
    } else {
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %d", [error domain], [error code]);
    }
    
    return totalFreeSpace;
}

- (void)getDivceSize{
    //可用大小
    struct statfs buf;
    long long freespace = -1;
    if(statfs("/var", &buf) >= 0){
        freespace = (long long)(buf.f_bsize * buf.f_bfree);
    }
    //总大小
    struct statfs buf1;
    long long maxspace = 0;
    if (statfs("/", &buf1) >= 0) {
        maxspace = (long long)buf1.f_bsize * buf1.f_blocks;
    }
    if (statfs("/private/var", &buf1) >= 0) {
        maxspace += (long long)buf1.f_bsize * buf1.f_blocks;
    }
    NSString * sizeStr = [NSString stringWithFormat:@"可用空间%0.2fG / 总空间%0.2fG",(double)freespace/1024/1024/1024,(double)maxspace/1024/1024/1024];
    NSLog(@"sizeStr= %@",sizeStr);
    
}

@end


#pragma mark ************************************************************************************************************
#pragma mark AppManager
#pragma mark ************************************************************************************************************
@interface AppManager()  {
    BOOL mIsReview;
}
@end

@implementation AppManager
+ (AppManager *)shareInstance {
    static AppManager *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[AppManager alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        mIsReview = YES;
    }
    return self;
}

- (BOOL)isReview {
    return mIsReview;
}

- (void)setIsReview:(BOOL) isReview {
    mIsReview = isReview;
}

- (NSString *)deviceID {
    NSString *servicename = @"com.tts8.tczww.deviceid";
    NSString *username = @"uniquedeviceid";
    NSError *error = nil;
    NSString *strUniqueCode = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:servicename error:&error];
    if (strUniqueCode == nil) {
        NSString   *str = @"";
        for (int i = 0; i < 4; i++) {
            NSUInteger a = 0;
            while (a < 1000000000) {
                a = arc4random()%RAND_MAX;
            }
            str = [NSString stringWithFormat:@"%lu%@",(unsigned long)a,str];
        }
        strUniqueCode = str;
        BOOL saved = [SFHFKeychainUtils storeUsername:username andPassword:strUniqueCode forServiceName:servicename updateExisting:YES error:&error];
        if (!saved) {
            NSLog(@"ERROR 保存密码到keychain时出错：%@", error);
        }
    }
    return  [JpMD5Util getmd5WithString:strUniqueCode];
}

- (NSString *)installID {
    NSString *servicename = @"com.tts8.tczww.installid";
    NSString *username = @"uniqueinstallid";
    NSError *error = nil;
    NSString *strUniqueCode = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:servicename error:&error];
    if (strUniqueCode == nil) {
        NSString   *str = @"";
        for (int i = 0; i < 4; i++) {
            NSUInteger a = 0;
            while (a < 1000000000) {
                a = arc4random()%RAND_MAX;
            }
            str = [NSString stringWithFormat:@"%lu%@",(unsigned long)a,str];
        }
        strUniqueCode = str;
        BOOL saved = [SFHFKeychainUtils storeUsername:username andPassword:strUniqueCode forServiceName:servicename updateExisting:YES error:&error];
        if (!saved) {
            NSLog(@"ERROR 保存密码到keychain时出错：%@", error);
        }
    }
    return  [JpMD5Util getmd5WithString:strUniqueCode];
}


@end

